import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Checkbox, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useState, useEffect, useRef } from 'react';
import DataForm from './components/DataForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import RelatedCustomers from './components/RelatedCustomers';

const tableId = uniqueId('tauTable-');

const Managers = () => {
  const [modal, setModal] = useState({
    show: false,
    record: {},
  });
  const [showAssociated, setShowAssociated] = useState(false);
  const [counts, setCounts] = useState({
    cc: [],
    bus: [],
    sc: [],
    rs: [],
    customer: [],
  });
  const { managersStore: store } = useStore();
  const [showOrders, setShowOrders] = useState(false);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const cc = await fetchCCOrderCounts();
        const bus = await fetchBUSOrderCounts();
        const sc = await fetchSCOrderCounts();
        const rs = await fetchRSOrderCounts();
        setCounts({
          ...counts,
          cc,
          bus,
          sc,
          rs,
        });
      })();
    } else {
      setCounts({
        ...counts,
        cc: [],
        bus: [],
        sc: [],
        rs: [],
      });
    }
  }, [showOrders, store.data, store.from, store.to]);

  useEffect(() => {
    if (showAssociated) {
      (async () => {
        const customer = await fetchCustomerCounts();
        setCounts({
          ...counts,
          customer,
        });
      })();
    } else {
      setCounts({
        ...counts,
        customer: [],
      });
    }
  }, [showAssociated, store.data]);

  async function fetchCustomerCounts() {
    const promiseAry = store.data.map(async (p) => await store.getManagersInfoCount({
      search: {
        receiver: p.id,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  // 获取包车订单
  async function fetchCCOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      return store.api.ordersCount({
        search: {
          orderType: 1,
          attribution: {
            targetType: 'MANAGER',
            targetId: p.id,
            targetName: p.fullname,
          },
          fromTime: store.from,
          toTime: store.to,
        },
      }).then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }

  // 获取巴士订单
  async function fetchBUSOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      return store.api.ordersCount({
        search: {
          attribution: {
            targetType: 'MANAGER',
            targetId: p.id,
            targetName: p.fullname,
          },
          orderType: 3,
          fromTime: store.from,
          toTime: store.to,
        },
      }).then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }

  // 获取专线订单
  async function fetchSCOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      return store.api.ordersCount({
        search: {
          attribution: {
            targetType: 'MANAGER',
            targetId: p.id,
            targetName: p.fullname,
          },
          orderType: 2,
          fromTime: store.from,
          toTime: store.to,
        },
      }).then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }

  // 获取拼车订单
  async function fetchRSOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      return store.api.ordersCount({
        search: {
          attribution: {
            targetType: 'MANAGER',
            targetId: p.id,
            targetName: p.fullname,
          },
          orderType: 4,
          fromTime: store.from,
          toTime: store.to,
        },
      }).then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }


  // 获取列表数据
  const handleOnSearch = (params) => {
    const { registerAddr, status, getOnDate, orderDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      registerAddr,
      status,
      from,
      to,
      orderDate,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleCreateManagers = () => {
    setModal({
      show: 'add',
      record: {},
    });
  };

  // 点击打开编辑
  const handleOpenEdit = (record) => {
    setModal({
      show: 'edit',
      record,
    });
  };

  // 点击打开查看
  const handelView = (record, type) => {
    switch (type) {
      case 'view':
        setModal({
          show: 'view',
          record,
        });
        break;
      case 'viewCustomer':
        setModal({
          show: 'viewCustomer',
          record,
        });
        break;
      default:
        break;
    }
  };


  // 查看包车订单
  const handleOpenCCOrder = async (record) => {
    setModal({ show: 'ccOrder', record });
  };

  // 查看巴士订单
  const handleOpenBUSOrder = async (record) => {
    setModal({ show: 'busOrder', record });
  };

  // 查看专线订单
  const handleOpenSCOrder = async (record) => {
    setModal({ show: 'scOrder', record });
  };

  // 查看拼车订单
  const handleOpenRSOrder = async (record) => {
    setModal({ show: 'rsOrder', record });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 删除客户经理
  const handleRemove = (record) => {
    Dialog.confirm({
      title: t`删除该客户经理`,
      onOk: async () => {
        try {
          await store.remove(record?.username);
          Message.success({ content: t`客户经理删除成功` });
        } catch (error) {
          Message.error({ content: t`客户经理删除失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { username, iphone, accountManagerInfo, discountInfo } = result;
        const params = {
          username,
          mobile: iphone,
          accountManagerInfo,
          discountInfo,
        };
        await store.create(params, { appId: global.config[global.ENV].mpAppId });
        Message.success({ content: t`客户经理创建成功` });
      } catch (e) {
        Message.error({ content: t`客户经理创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-addManagers',
            title: t`添加客户经理`,
            type: 'primary',
            onClick: handleCreateManagers,
          },
        ]}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`注册开始时间`, t`注册结束时间`],
            },
          },
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`订单开始时间`, t`订单结束时间`],
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showDriver',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowAssociated(v)}>{t`查看关联客户`}</Checkbox>,
          },
          {
            name: 'cbx-showOrders',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowOrders(v)}>{t`查看订单`}</Checkbox>,
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('fullname', {
              cell: (v, i, r) => <Button type="primary" text onClick={() => handelView(r, 'view')}>{v}</Button>,
            }),
            column('mobile', {}),
            column('lastLogin', {}),
            column('accountManagerInfo.registerTime', {}),
            column('associatedCustomers', {
              cell: (v, i, r) => <Button type="primary" text onClick={() => handelView(r, 'viewCustomer')}>{counts.customer.find((p) => p.id === r.id)?.count || 0}</Button>,
            }),
            column('orderCommissionTotal', {}),
            column('ccOrderCount', { width: 88, cell: (v, _, r) => <Button type="primary" text onClick={() => handleOpenCCOrder(r)}>{counts.cc.find((n) => n.id === r.id)?.count || 0}</Button> }),
            column('busOrderCount', { width: 88, cell: (v, _, r) => <Button type="primary" text onClick={() => handleOpenBUSOrder(r)}>{counts.bus.find((n) => n.id === r.id)?.count || 0}</Button> }),
            column('scOrderCount', { width: 88, cell: (v, _, r) => <Button type="primary" text onClick={() => handleOpenSCOrder(r)}>{counts.sc.find((n) => n.id === r.id)?.count || 0}</Button> }),
            column('rsOrderCount', { width: 88, cell: (v, _, r) => <Button type="primary" text onClick={() => handleOpenRSOrder(r)}>{counts.rs.find((n) => n.id === r.id)?.count || 0}</Button> }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 180,
              cell: (_, __, managers) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(managers)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleRemove(managers)} >{t`删除`}</Button>
                </>),
            },
          ].filter((c) => c.dataIndex !== 'associatedCustomers' || showAssociated)
            .filter((c) => c.dataIndex !== 'ccOrderCount' || showOrders)
            .filter((c) => c.dataIndex !== 'busOrderCount' || showOrders)
            .filter((c) => c.dataIndex !== 'scOrderCount' || showOrders)
            .filter((c) => c.dataIndex !== 'rsOrderCount' || showOrders)}
        />
      </div>
      <Drawer
        visible={modal.show === 'edit' || modal.show === 'view' || modal.show === 'add'}
        title={ENUMS.TITLE_TEXT[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="90%"
      >
        <DataForm
          username={modal.record?.username}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.show === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal.show === 'viewCustomer'}
        title={t`查看关联客户`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="90%"
      >
        <RelatedCustomers
          username={modal.record?.username}
          modal={modal}
          onCancel={handleCancel}
        />
      </Drawer>
      <ComponentsDrawer
        modal={[modal.show]}
        queryParams={{
          attribution: {
            targetType: 'MANAGER',
            targetId: modal.record?.id,
            targetName: modal.record?.fullname,
          },
        }}
        name={modal.record?.fullname}
        onCancel={handleCancel}
      />
    </TauPage>
  );
};

export default observer(Managers);
